<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<script>
			function KeyEvent(e, cmd) {
				//alert(e.keyCode);
				if(e.keyCode == 37)
					cmd.call(cpu, 6) // left
				else if(e.keyCode == 38)
					cmd.call(cpu, 4); // up
				else if(e.keyCode == 39)
					cmd.call(cpu, 7); // right
				else if(e.keyCode == 40)
					cmd.call(cpu, 5); // down
				else if(e.keyCode == 13)
					cmd.call(cpu, 3); // start
				else if(e.keyCode == 220)
					cmd.call(cpu, 2); // select
				else if(e.keyCode == 32)
					cmd.call(cpu, 0); // A
				else if(e.keyCode == 16)
				cmd.call(cpu, 1); // B
			}
			function loadGame(name) {
				var buttons = document.getElementById('buttons');
				buttons.parentNode.removeChild(buttons);

				display = document.getElementById('display').getContext('2d');

				var data = document.createElement('script');
				data.src = '../roms/' + name + '.js';
				document.body.appendChild(data);
				var emul = document.createElement('script');
				emul.src = '../jnes/jnes.js';
				setTimeout(function() { document.body.appendChild(emul); }, 100);

				window.addEventListener("keydown", function (e) { KeyEvent(e, cpu.btnDown); }, false)
				window.addEventListener("keyup", function (e) { KeyEvent(e, cpu.btnUp); }, false)

				var lastLoops = 0;
				var lastFrames = 0;
				var fpsSpan = document.getElementById('fps');
				var freqSpan = document.getElementById('freq');
				setInterval(function() {
					fpsSpan.innerHTML = framesCount - lastFrames;
					freqSpan.innerHTML = (loop - lastLoops) / 1000000.0;
					lastLoops = loop;
					lastFrames = framesCount;
				}, 1000);
			}
		</script>
	</head>
	<body>
		<div id="buttons">
			<button type="button" onclick="loadGame('mario')">mario</button>
			<button type="button" onclick="loadGame('battlecity')">battlecity</button>
			<button type="button" onclick="loadGame('loderunner')">loderunner</button>
			<button type="button" onclick="loadGame('baloon_fight')">baloon fight</button>
			<button type="button" onclick="loadGame('sky_destroyer')">sky destroyer</button>
			<button type="button" onclick="loadGame('NEStress')">NEStress</button>
			<button type="button" onclick="loadGame('official_only')">test [CPU]</button>
			<button type="button" onclick="loadGame('palette_ram')">test [palette ram]</button>
			<button type="button" onclick="loadGame('sprite_ram')">test [sprite ram]</button>
		</div>
		<canvas height="240" width="256" id="display">
			Здесь должен быть canvas :(
		</canvas>
        <div id="info">
            FPS: <span id="fps">---</span> кадров/сек<br>
            freq: <span id="freq">---</span> МГц
        </div>
	</body>
</html>
